<template>
  <div class="batch-sync-lawyers">
    <el-dialog
      v-model="dialogVisible"
      title="批量同步律师到用户系统"
      width="600px"
      @close="handleClose"
    >
      <div class="sync-content">
        <el-alert
          title="同步说明"
          type="info"
          description="将选中的律师信息同步到用户管理系统，同步后律师可以使用手机号登录系统。"
          :closable="false"
          class="sync-tip"
        />

        <div class="sync-options">
          <h4>同步选项</h4>
          <el-radio-group v-model="syncType">
            <el-radio :label="1">同步所有可同步律师</el-radio>
            <el-radio :label="2">按律所筛选</el-radio>
          </el-radio-group>
        </div>

        <div v-if="syncType === 2" class="lawfirm-filter">
          <el-select
            v-model="selectedLawfirm"
            placeholder="请选择律所"
            filterable
            clearable
            style="width: 100%"
          >
            <el-option
              v-for="lawfirm in lawfirmOptions"
              :key="lawfirm.id"
              :label="lawfirm.title"
              :value="lawfirm.id"
            />
          </el-select>
        </div>

        <div class="sync-preview" v-loading="loadingPreview">
          <h4>可同步律师预览</h4>
          <div class="lawyer-count">
            共找到
            <span class="count">{{ syncableCount }}</span>
            位可同步律师
          </div>
          <el-table :data="syncableLawyers" height="300" border v-if="syncableLawyers.length > 0">
            <el-table-column prop="name" label="律师姓名" width="120" />
            <el-table-column prop="mobile" label="手机号" width="120" />
            <el-table-column prop="lawfirm" label="所属律所" show-overflow-tooltip />
          </el-table>
        </div>
      </div>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button
            type="primary"
            @click="handleBatchSync"
            :loading="syncing"
            :disabled="syncableCount === 0"
          >
            开始同步
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, onMounted } from 'vue'
  import { useLawyerStore } from '@/store/lawyer'
  // 使用lawyerStore中的律所相关方法
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { Lawyer, Lawfirm } from '@/types/lawyer'

  const props = defineProps<{
    modelValue: boolean
  }>()

  const emit = defineEmits<{
    'update:modelValue': [value: boolean]
    'sync-success': []
  }>()

  const lawyerStore = useLawyerStore()

  // 状态管理
  const dialogVisible = ref(false)
  const loadingPreview = ref(false)
  const syncing = ref(false)
  const syncType = ref(1) // 1-全部，2-按律所
  const selectedLawfirm = ref<number | null>(null)
  const lawfirmOptions = ref<Lawfirm[]>([])
  const syncableLawyers = ref<Lawyer[]>([])
  const syncableCount = ref(0)

  // 监听对话框显示状态
  watch(
    () => props.modelValue,
    newVal => {
      dialogVisible.value = newVal
      if (newVal) {
        loadLawfirmList()
        loadSyncableLawyers()
      }
    }
  )

  watch([syncType, selectedLawfirm], () => {
    loadSyncableLawyers()
  })

  // 加载律所列表
  const loadLawfirmList = async () => {
    try {
      const response = await lawyerStore.getLawfirmListAction({ page: 1, limit: 1000 })
      if (response.code === 0) {
        lawfirmOptions.value = response.data
      }
    } catch (error) {
      console.error('加载律所列表失败:', error)
    }
  }

  // 加载可同步律师列表
  const loadSyncableLawyers = async () => {
    loadingPreview.value = true
    try {
      const params = {
        firm_id: syncType.value === 2 ? selectedLawfirm.value : undefined,
        sync_status: 'unsynced', // 只获取未同步的律师
      }
      const response = await lawyerStore.getSyncableLawyersAction(params)
      if (response.code === 0) {
        syncableLawyers.value = response.data.list || []
        syncableCount.value = response.data.count || 0
      } else {
        ElMessage.error(response.msg || '获取可同步律师列表失败')
      }
    } catch (error) {
      ElMessage.error('获取可同步律师列表失败')
    } finally {
      loadingPreview.value = false
    }
  }

  // 批量同步律师
  const handleBatchSync = async () => {
    try {
      await ElMessageBox.confirm(
        `确定要同步 ${syncableCount.value} 位律师到用户系统吗？`,
        '确认同步',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )

      syncing.value = true

      // 收集所有可同步律师的ID
      const lawyerIds = syncableLawyers.value.map(lawyer => lawyer.id)

      const response = await lawyerStore.batchSyncLawyersAction({
        lawyer_ids: lawyerIds,
      })

      if (response.code === 0) {
        ElMessage.success(
          `成功同步 ${response.data?.success || 0} 位律师，失败 ${response.data?.fail || 0} 位`
        )
        emit('sync-success')
        handleClose()
      } else {
        ElMessage.error(response.msg || '同步失败')
      }
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('同步失败')
      }
    } finally {
      syncing.value = false
    }
  }

  // 关闭对话框
  const handleClose = () => {
    dialogVisible.value = false
    emit('update:modelValue', false)
    // 重置状态
    syncType.value = 1
    selectedLawfirm.value = null
    syncableLawyers.value = []
    syncableCount.value = 0
  }
</script>

<style scoped>
  .batch-sync-lawyers {
    .sync-content {
      .sync-tip {
        margin-bottom: 20px;
      }

      .sync-options {
        margin-bottom: 20px;

        h4 {
          margin-bottom: 10px;
          font-size: 14px;
          font-weight: 500;
        }
      }

      .lawfirm-filter {
        margin-bottom: 20px;
      }

      .sync-preview {
        h4 {
          margin-bottom: 10px;
          font-size: 14px;
          font-weight: 500;
        }

        .lawyer-count {
          margin-bottom: 10px;
          font-size: 13px;
          color: #666;

          .count {
            color: #409eff;
            font-weight: bold;
          }
        }
      }
    }

    .dialog-footer {
      text-align: right;
    }
  }
</style>
